<?php
	
	namespace Aspic\Model;
	use Aspic as A;
	
	/**
	 * Tamper columns which have special type set and modify value to transform it in an object for certain special types
	*/
	class STRow extends Row {

		/**
		 *
		 * @var bool Define if tampering is enabled
		 */
		protected $_tamperData;


		public function __construct(DataModel $dataModel, $returnNullIfEmpty = true) {
			parent::__construct($dataModel, $returnNullIfEmpty);
			
			$this->_tamperData = true;
		}
		
		public function setTamperData($val) {
			$this->_tamperData = (bool)$val;
		}
		
		public function getTamperData() {
			return $this->_tamperData;
		}
		
		public function __set($var, $value) {
			if ($this->hasDataModel() AND $this->_dataModel->colExists($var)) {
				$col = $this->_dataModel->getCol($var);
				
				if (is_string($value) AND $this->getTamperData()) {
					if($col['specialTypeClass']) {
						$obj = $this->getStObject($col, $value);
					}
				}
				
				if (isset($obj)) {
					parent::__set($var, $obj);
				}
				else {
					parent::__set($var, $value);
				}
				
			}
			else {
				return parent::__set($var, $value);
			}
			
		}
		
		public function &get($var) {
			$data = &parent::get($var);
			
			if (is_object($data)) {
				$this->_hasBeenModified = true;
			}
			
			return $data;
		}
		
		/**
		 * Return a special type object from string that represent it
		 * @param array $col An array representing a column (see DataModel)
		 * @param string $value
		 * @return StorableObjectInterface
		 */
		protected function getStObject($col, $value) {
			$obj = call_user_func(array($col['specialTypeClass'], 'fromStorableString'), $value);
			
			return $obj;
		}
		
		/**
		 * Return the storable value of a given object implementing \Aspic\Model\StorableObjectInterface
		 * @param \Aspic\StorableObjectInterface $obj
		 * @return type
		 * @throws A\Exception
		 */
		protected function getStObjectStorableValue($obj) {
			if (!$obj instanceof A\StorableObjectInterface) {
				throw new A\Exception('Given object is not an instance of Aspic\StorableObjectInterface. Cannot convert it to storable value');
			}
			
			$value = $obj->toStorableString();
			
			return $value;
		}
		
		/**
		 * Return the storable value of a column
		 * @param type $col
		 * @return null
		 */
		public function getStorableValue($col) {
			if ($this->_dataModel->colExists($col)) {
				$col = $this->_dataModel->getCol($col);
				$value = $this->__get($col);
				
				// Value could not be an object if not yet transform into object by $this->__set
				if($col['specialType'] AND is_object($value)) {
					return $this->getStObjectStorableValue($value, $col);
				}
				else {
					return $value;
				}
			}
			else {
				return null;
			}
		}
		
	}
	
?>